const express = require("express");
const cors = require("cors");
const axios = require("axios");
const NodeCache = require("node-cache");
const path = require("path");

const app = express();
const PORT = process.env.PORT || 3000;

// 创建缓存实例，缓存时间为10分钟
const cache = new NodeCache({ stdTTL: 600 });

app.use(cors());
app.use(express.json());
app.use(express.static("public"));

// 提供主页
app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "public", "index.html"));
});

// 获取单个包的下载统计
app.get("/api/downloads/:packageName", async (req, res) => {
  const { packageName } = req.params;
  const { period = "last-month" } = req.query;

  const cacheKey = `${packageName}-${period}`;
  const cachedData = cache.get(cacheKey);

  if (cachedData) {
    return res.json(cachedData);
  }

  try {
    // 获取下载统计数据
    const downloadsResponse = await axios.get(
      `https://api.npmjs.org/downloads/point/${period}/${packageName}`
    );

    // 获取包的基本信息
    const packageResponse = await axios.get(
      `https://registry.npmjs.org/${packageName}`
    );

    const result = {
      package: packageName,
      downloads: downloadsResponse.data.downloads,
      period: period,
      description: packageResponse.data.description || "暂无描述",
      version: packageResponse.data["dist-tags"]?.latest || "未知",
      homepage: packageResponse.data.homepage || "",
      repository: packageResponse.data.repository?.url || "",
      keywords: packageResponse.data.keywords || [],
      author:
        packageResponse.data.author?.name ||
        packageResponse.data.author ||
        "未知",
      license: packageResponse.data.license || "未知",
    };

    cache.set(cacheKey, result);
    res.json(result);
  } catch (error) {
    console.error("获取包信息失败:", error.message);
    if (error.response?.status === 404) {
      res.status(404).json({ error: "包不存在" });
    } else {
      res.status(500).json({ error: "服务器错误" });
    }
  }
});

// 获取多个包的下载统计对比
app.post("/api/compare", async (req, res) => {
  const { packages, period = "last-month" } = req.body;

  if (!packages || !Array.isArray(packages) || packages.length === 0) {
    return res.status(400).json({ error: "请提供要比较的包名数组" });
  }

  try {
    const results = await Promise.all(
      packages.map(async (packageName) => {
        const cacheKey = `${packageName}-${period}`;
        const cachedData = cache.get(cacheKey);

        if (cachedData) {
          return cachedData;
        }

        try {
          const downloadsResponse = await axios.get(
            `https://api.npmjs.org/downloads/point/${period}/${packageName}`
          );

          const packageResponse = await axios.get(
            `https://registry.npmjs.org/${packageName}`
          );

          const result = {
            package: packageName,
            downloads: downloadsResponse.data.downloads,
            period: period,
            description: packageResponse.data.description || "暂无描述",
            version: packageResponse.data["dist-tags"]?.latest || "未知",
            author:
              packageResponse.data.author?.name ||
              packageResponse.data.author ||
              "未知",
          };

          cache.set(cacheKey, result);
          return result;
        } catch (error) {
          return {
            package: packageName,
            error: error.response?.status === 404 ? "包不存在" : "获取失败",
            downloads: 0,
          };
        }
      })
    );

    // 按下载量排序
    results.sort((a, b) => (b.downloads || 0) - (a.downloads || 0));

    res.json(results);
  } catch (error) {
    console.error("比较包下载量失败:", error.message);
    res.status(500).json({ error: "服务器错误" });
  }
});

// 获取包的历史下载数据
app.get("/api/downloads/:packageName/range/:start/:end", async (req, res) => {
  const { packageName, start, end } = req.params;

  const cacheKey = `${packageName}-range-${start}-${end}`;
  const cachedData = cache.get(cacheKey);

  if (cachedData) {
    return res.json(cachedData);
  }

  try {
    const response = await axios.get(
      `https://api.npmjs.org/downloads/range/${start}:${end}/${packageName}`
    );

    cache.set(cacheKey, response.data);
    res.json(response.data);
  } catch (error) {
    console.error("获取历史数据失败:", error.message);
    if (error.response?.status === 404) {
      res.status(404).json({ error: "包不存在" });
    } else {
      res.status(500).json({ error: "服务器错误" });
    }
  }
});

app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});
